package com.zone.vehicle.superapp.view.setting;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.fastjson.JSON;
import com.zone.sdk.module.account.entity.LoginEntity;
import com.zone.sdk.module.account.entity.UserInfoEntity;
import com.zone.sdk_api.common.Content;
import com.zone.vehicle.superapp.R;
import com.zone.vehicle.superapp.common.ContentAccount;
import com.zone.vehicle.superapp.databinding.FragmentSettingBinding;
import com.zone.vehicle.superapp.model.LoginViewModel;
import com.zone.vehicle.superapp.model.ViewModelFactory;
import com.zone.vehicle.superapp.utils.SharedPreferencesUtil;
import com.zone.vehicle.superapp.view.common.base.BaseFragment;
import com.zone.vehicle.superapp.view.common.listener.ActionListener;
import com.zone.vehicle.lib.view.widget.CustomDialog;

import org.apache.commons.lang3.ObjectUtils;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class SettingFragment extends BaseFragment implements View.OnClickListener {

    private static final String TAG = SettingFragment.class.getSimpleName();

    private FragmentSettingBinding binding;
    private CustomDialog dialog;
    private ActionListener listener;
    private LoginViewModel viewModel;

    public SettingFragment(ActionListener listener){
        this.listener = listener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentSettingBinding.inflate(inflater);
        viewModel = new ViewModelProvider(this, new ViewModelFactory())
                .get(LoginViewModel.class);
        init();
        return binding.getRoot();
    }

    private void init(){

        addListener(listener);
        binding.btnBack.setOnClickListener(this);
        binding.item1.setOnClickListener(this);
        binding.item2.setOnClickListener(this);
        binding.item3.setOnClickListener(this);
        binding.item4.setOnClickListener(this);
        binding.item5.setOnClickListener(this);

        viewModel.getLoginEntity().observe(getViewLifecycleOwner(), new Observer<LoginEntity>() {
            @Override
            public void onChanged(LoginEntity loginEntity) {
                if (ObjectUtils.isEmpty(loginEntity)){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(), "退出登录", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });

        initDialog();
    }

    private void initDialog(){
        dialog = new CustomDialog(getContext());
        dialog.setTitle("发现新版本");
        dialog.setSubTitle("V 1.0.1");
        dialog.setMessage("更新内容：\n 1.提示消息提示消息提示\n 2.消息提示消息提示消息提示\n 3.消息提示消息提示消息");
        dialog.setOnClickBottomListener(new CustomDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                Toast.makeText(getContext(), "开始下载安装", Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }

            @Override
            public void onNegtiveClick() {
                Toast.makeText(getContext(), "取消安装", Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
//        File apk = new File(requireActivity().getCacheDir(), "com.zone.testsocket.apk");
//        String apkFilePath = apk.getAbsolutePath();
//        copyAssetAndWrite("com.zone.testsocket.apk");
        switch (v.getId()){
            case R.id.item1:
//                AndroidP.install28(requireContext(), apkFilePath);
                break;
            case R.id.item2:
//                Intent intent = requireActivity().getPackageManager().getLaunchIntentForPackage("com.zone.testsocket");
//                if (intent != null) {
//                    intent.setPackage(null);
//                    requireActivity().startActivity(intent);
//                }
                break;
            case R.id.item3:
//                AndroidP.uninstall(requireContext(), "com.zone.testsocket");
                break;
            case R.id.item4:
                break;
            case R.id.item5:
                Object o = SharedPreferencesUtil.getInstance(getContext()).getObject(Content.USER_INFO, UserInfoEntity.class);
                Log.d(TAG, "USER_INFO="+ JSON.toJSONString(o));
                if (ObjectUtils.isNotEmpty(o)) {
                    viewModel.logout(getContext());
                    finish();
                }
                break;
            case R.id.btn_back:
//                onBack();
                finish();
                break;
        }
    }

    /**
     * 将asset文件写入缓存
     */
    private boolean copyAssetAndWrite(String fileName){
        try {
            File cacheDir=requireActivity().getCacheDir();
            if (!cacheDir.exists()){
                cacheDir.mkdirs();
            }
            File outFile =new File(cacheDir,fileName);
            if (!outFile.exists()){
                boolean res=outFile.createNewFile();
                if (!res){
                    return false;
                }
            }else {
                if (outFile.length()>10){//表示已经写入一次
                    return true;
                }
            }
            InputStream is=requireActivity().getAssets().open(fileName);
            FileOutputStream fos = new FileOutputStream(outFile);
            byte[] buffer = new byte[1024];
            int byteCount;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            is.close();
            fos.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    private void logout(){
        SharedPreferencesUtil.getInstance(getContext()).removeSP(ContentAccount.USER_ID);
    }

    private void showUpdateDialog(){
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
    }
}